package Biz;

import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import Model.User;


/**
 * Session Bean implementation class UserBean
 */
@Stateless
@LocalBean
public class UserBean {
    @PersistenceContext(name = "NucleicAcidSystem")
    private EntityManager manager;

    public UserBean() {
    }
    
    public String queryUser(String username, String password) {
    	String type = "INVALID";
    	List<User> results = null;
		try 
		{         
			String jpql = "select u from User u where u.username = ?1 and u.password = ?2";
			Query q = manager.createQuery(jpql);
			q.setParameter(1, username);
			q.setParameter(2, password);
			results = q.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (results != null && results.size() != 0) 
			type = results.get(0).getType();
		System.out.println(type);
        return type;
   }
    
   public boolean addUser(String username, String password, String type) {
	   if (userExists(username))
			return false;
	   if (type == null)
		   type = "STUDENT";
	   User u = new User();
	   u.setUsername(username);
	   u.setPassword(password);
	   u.setType(type);
	   try {
		   manager.persist(u);
	   } catch (Exception e) {
		   e.printStackTrace();
	   } 
	   return true;
   }
   
   public boolean userExists(String username) {
	    List results = null;
		try 
		{         
			String jpql = "select u from User u where u.username = ?1";
			Query q = manager.createQuery(jpql);
			q.setParameter(1, username);
			results = q.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (results != null && results.size() > 0)
			return true;
		else
			return false;
    }
}
